<?php

namespace App\Http\Services;

use App\Http\Model\FinanceNotifyLog;
use App\Http\Model\Hint;
use App\Http\Model\FinanceBank as FinanceBankModel;
use App\Http\Model\FinanceWithdrawOrder as FinanceWithdrawOrderModel;
use App\Http\Model\UserVerify as UserVerifyModel;
use App\Lib\CloudAccount;
use App\Lib\CloudAccountRsa;

class FinanceBankServices extends CommonServices
{
    protected $request;
    protected $financeBankModel;
    protected $financeWithdrawOrderModel;
    protected $userVerifyModel;
    protected $financeNotifyModel;

    public function __construct(FinanceBankModel $financeBankModel, FinanceWithdrawOrderModel $financeWithdrawOrderModel, UserVerifyModel $userVerifyModel ,FinanceNotifyLog $financeNotifyLog)
    {
        $this->financeBankModel = $financeBankModel;
        $this->financeWithdrawOrderModel = $financeWithdrawOrderModel;
        $this->userVerifyModel = $userVerifyModel;
        $this->financeNotifyModel = $financeNotifyLog;
    }

    public function bankNameList()
    {
        $code = Hint::SUCCESS;
        $data = config('bank')['cloud_account'] ?? [];
        return compact('code', 'data');
    }

    public function bindBank($params = [])
    {
        $checkField = ['owner_name', 'idcard_no', 'bank_name', 'bank_no'];// 'bank_address', 'bank_branch_name',
        $params['idcard_no'] = isset($params['idcard_no'])?strtolower($params['idcard_no']):'';
        $code = Hint::SUCCESS;
        $data = [];

        do {
            try {
                // self session add params user_id
                $userId = $_SESSION['user_id'] ?? 0;

                // todo 增加到返回data中记录日志
                $data['sessionUserId'] = $userId;

                if (empty($userId)) {
                    $code = Hint::LOGIN_OUT;
                    break;
                }

                $inputParams = [];
                if (empty($params)) {
                    $code = Hint::PARAM_ERROR;
                    $data['error_msg'] = '参数不能为空';
                    break;
                }

                foreach ($checkField as $field) {
                    if (array_key_exists($field, $params)) {
                        $inputParams[$field] = $params[$field];
                    }
                }

                // todo 增加到返回data中记录日志
                $data['inputParams'] = $inputParams;

                if (count($inputParams) != count($checkField)) {
                    $code = Hint::PARAM_ERROR;
                    $data['error_msg'] = '参数不完整';
                    break;
                }

                // 判断银行卡名称是否存在
                $bankNameList = $this->bankNameList();
                if (!in_array($inputParams['bank_name'], $bankNameList['data'])) {
                    $code = Hint::PARAM_ERROR;
                    $data['error_msg'] = '该银行卡不支持';
                    break;
                }
                //银行卡信息与本账号实名认证信息是否一致
                $user_verify = $this->userVerifyModel->getInfoByUser(array('user_id'=>$userId ,'result_code'=>1000));
                if(empty($user_verify) || $user_verify['idcard_number'] != $params['idcard_no']){
                    $code = Hint::PARAM_ERROR;
                    $data['error_msg'] = '银行卡信息与本账号实名认证信息不一致';
                    break;
                }
                $inputParams['user_id'] = $userId;
                // 查询银行卡是否存在
                $checkBankNo = $this->financeBankModel->getBankCloud(['bank_no' => $inputParams['bank_no']]);
                if (!empty($checkBankNo)) {
                    $code = Hint::BANK_EXIST;
                    break;
                }
                //判断该账户的同实名身份证号是否已经绑定
                $checkBankNo = $this->financeBankModel->getBankCloud(['idcard_no' => $inputParams['idcard_no']]);
                if(!empty($checkBankNo)){
                    $code = Hint::ERR_FAIL;
                    $data['error_msg'] = '同实名身份证号只能绑定一张银行卡';
                    break;
                }
                // 查询限制银行卡绑定数 int
                //$withdrawBankNumber = $this->financeWithdrawOrderModel->withdrawBankNumber();
                // 查询银行卡总数
//                $checkBankNoCount = $this->financeBankModel->get(['user_id' => $userId]);
//                if (count($checkBankNoCount) >= $withdrawBankNumber) {
//                    $code = Hint::BANK_MAX_COUNT;
//                    break;
//                }

                /*// 查询用户身份认证信息
                $userInfoIDCardData = $this->userVerifyModel->getInfoByUser(['user_id' => $userId]);

                // todo 增加到返回data中记录日志
                $data['userInfoIDCardData'] = $userInfoIDCardData;

                if (empty($userInfoIDCardData)) {
                    $code = Hint::USER_VERIFY_ID_NUMBER_NAME_NOT_MATCH;
                    $data['error_msg'] = '身份未认证';
                    break;
                }

                // 校验开户名与身份证是否一致
                if ($inputParams['owner_name'] != $userInfoIDCardData['idcard_name']) {
                    $code = Hint::USER_VERIFY_ID_NUMBER_NAME_NOT_MATCH;
                    $data['error_msg'] = '开户名与身份证名称不一致';
                    break;
                }*/

                // 校验银行卡
                $cloudAccountInstance = CloudAccountRsa::getInstance(2);
                $cloudAccountInstance->requestData = [
                    'bank_no' => $inputParams['bank_no'],// 银行卡号
                    'idcard_number' => $inputParams['idcard_no'],// 银行开户身份证
                    'idcard_name' => $inputParams['owner_name'],// 银行卡开户姓名
                ];

                // todo 增加到返回data中记录日志
                $data['cloudAccountCheckBankParams'] = $cloudAccountInstance->requestData;

                $result = $cloudAccountInstance->verifyBankCard();
                $data['verifyBankCardResult'] = $result;
                $result = json_decode($result, true);
                // 判断接口返回逻辑
                $resultCode = $result['code'] ?? 'error';
                if (empty($result) or $resultCode == 'error') {
                    $code = Hint::PARAM_ERROR;
                    $data['error_msg'] = '接口异常';
                    $data['error_result'] = $result;
                    break;
                }
                if ($result['code'] != '0000') {
                    $code = Hint::PARAM_ERROR;
                    $data['error_msg'] = $result['message'];
                    $data['error_result'] = $result;
                    break;
                }

                // 创建银行卡
                $data['bank_id'] = $this->financeBankModel->bindBankCloud($inputParams);
                if ($data['bank_id'] <= 0) {
                    $code = Hint::BANK_CREATE_FAIL;
                    $data['error_msg'] = '银行卡创建失败';
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::NOT_ALLOWED;
                $data['error_msg'] = $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'data');
    }

    public function editBank($params = [])
    {
        $code = Hint::SUCCESS;
        $data = [];

        do {
            try {
                $userId = $_SESSION['user_id'] ?? 0;

                // todo 增加到返回data中记录日志
                $data['sessionUserId'] = $userId;

                if (empty($userId)) {
                    $code = Hint::LOGIN_OUT;
                    break;
                }

                // 查询用户所属银行卡是否存在
                $checkBankNo = $this->financeBankModel->getBankCloud(['bank_id' => $params['bank_id']]);
                if (empty($checkBankNo)) {
                    $code = Hint::BANK_NO_EXIST;
                    break;
                }

                // 判断值是否存在银行卡号
                if (!empty($params['bank_no'] ?? '')) {
                    // 查询他人银行卡号是否存在
                    $checkBankNo = $this->financeBankModel->get([['user_id', '!=', $userId], ['bank_no', '=', $params['bank_no']]]);
                    if (!empty($checkBankNo)) {
                        $code = Hint::BANK_EXIST;
                        break;
                    }

                    // 查询自己银行卡号是否存在
                    $checkBankNo = $this->financeBankModel->get([['bank_id', '!=', $params['bank_id']], ['user_id', '=', $userId], ['bank_no', '=', $params['bank_no']]]);
                    if (!empty($checkBankNo)) {
                        $code = Hint::BANK_EXIST;
                        break;
                    }
                }

                // 更新银行卡
                $data['bank_id'] = $this->financeBankModel->edit($params, true);
                if ($data['bank_id'] <= 0) {
                    $code = Hint::BANK_UPDATE_FAIL;
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::NOT_ALLOWED;
                $data['error_msg'] = $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'data');
    }

    public function removeBank($params = [])
    {
        $code = Hint::SUCCESS;
        $data = [];

        do {
            try {
                $userId = $_SESSION['user_id'] ?? 0;

                // todo 增加到返回data中记录日志
                $data['sessionUserId'] = $userId;

                if (empty($userId)) {
                    $code = Hint::LOGIN_OUT;
                    break;
                }

                // 查询用户所属银行卡是否存在
                $checkBankNo = $this->financeBankModel->getBankCloud(['bank_id' => $params['bank_id']]);
                if (empty($checkBankNo)) {
                    $code = Hint::BANK_NO_EXIST;
                    break;
                }

                // 查询银行卡是否存在未支付（未操作）的订单
                $checkOrder = $this->financeWithdrawOrderModel->queryOrder(['bank_id' => $params['bank_id'], 'status' => 0]);

                // todo 增加到返回data中记录日志
                $data['checkOrder'] = $checkOrder;

//                if (!empty($checkOrder)) {
//                    $code = Hint::BANK_EXIST_ORDER;
//                    break;
//                }

                // 删除银行卡
                $rest = $this->financeBankModel->removeBankCloud($params['bank_id']);
                if ($rest <= 0) {
                    $code = Hint::BANK_REMOVE_FAIL;
                    break;
                }

            } catch (\Exception $e) {
                $code = Hint::NOT_ALLOWED;
                $data['error_msg'] = $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'data');
    }

    public function getBankByUser($params = [])
    {
        $code = Hint::SUCCESS;
        $data = [];

        do {
            try {
                $userId = $_SESSION['user_id'] ?? 0;

                // todo 增加到返回data中记录日志
                $data['sessionUserId'] = $userId;

                if (empty($userId)) {
                    $code = Hint::LOGIN_OUT;
                    break;
                }
                $params['user_id'] = $userId;
                $params['result_code'] = 1000;
                $user_verify = $this->userVerifyModel->getInfoByUser($params);
                if(empty($user_verify) || empty($user_verify['idcard_number'])){
                    $code = Hint::USER_NOT_CERTIFICATION;
                    break;
                }
                $isSingle = $params['is_single'] ?? 0;
                if ($isSingle) {
                    /*if (empty($params['bank_id'] ?? '')) {
                        $code = Hint::PARAM_ERROR;
                        break;
                    }*/

                    $data['list'] = $this->financeBankModel->getBankCloud(['idcard_no'=>$user_verify['idcard_number']]);
                    if (empty($data)) {
                        $code = Hint::BANK_NO_EXIST;
                        break;
                    }
                }

                $list = $this->financeBankModel->getBankCloud(['idcard_no'=>$user_verify['idcard_number']]);
                if(!empty($list)){
                    $data['list'][] = $list;
                }else{
                    $data['list'] = [];
                }
                // 查询限制银行卡绑定数 int 绑定银行卡最大数
                //$data['bind_bank_max_number'] = $this->financeWithdrawOrderModel->withdrawBankNumber();
                $data['bind_bank_max_number'] = 1;
                // 剩余可绑定数
                $data['remain_bind_bank_number'] = $data['bind_bank_max_number'] - count($data['list']);

                //获取账户信息 0个体账户 1挂靠 2对公
                $user_company = $this->financeBankModel->getUserCompany($user_verify['idcard_number']);
                $data['user_type'] = empty($user_company) ? 0 : $user_company['type'];
                $data['user_Individual'] = 0;
                $data['withdraw_price'] = 0;
                $data['limit_price'] = $this->financeBankModel->limit_price;
                if($data['user_type'] == 0){
                    $user_register_cloud = $this->financeNotifyModel->getCloudUser($user_verify['idcard_number']);
                    if(in_array($user_register_cloud['status'] ,array(4,6))){
                        $data['user_Individual'] = 1;
                    }
                    $user_verify_users = $this->userVerifyModel->getAllIcCard($user_verify['idcard_number']);
                    $user_ids = array_column($user_verify_users ,'user_id');
                    $data['withdraw_price'] = $this->financeWithdrawOrderModel->getMonthPriceByUserIds($user_ids);
                }
            } catch (\Exception $e) {
                $code = Hint::NOT_ALLOWED;
                $data['error_msg'] = $e->getMessage();
                break;
            }
        } while (false);

        return compact('code', 'data');
    }
}
